const app = getApp()
let isRefreshing = true
import {uniConfig} from '../config/index'
import { useUCenterStore } from '@/stores/uCenter'
const store = useUCenterStore()
const uniRequest = (params = {}, url,method = 'GET') => {
  let data = params.query || {}
  const params_ = {
    appid: uniConfig.appId,
    appkey:uniConfig.appKey,
    'zt-tag':uniConfig.cmpappkey
  }
  const member = uni.getStorageSync('memberInfo');
  if(member && member.auth_code)params_['auth-code'] = member.auth_code
  return new Promise(async (resolve, reject) => {
    await uni.request({
      url: url,
      method: method,
      data: data,
      header: {
        'Content-Type': url.includes('mall/order/create/byCart')?'application/json':'application/x-www-form-urlencoded',
        ...params_
      },
      success: async sucInfo => {
        let responseData = sucInfo['data']
        if (responseData.success) {
          return resolve(responseData)
        } else {
          if (responseData['errcode'] == -100 || responseData['msg'].includes('用户未登录')) {            
            const pages = getCurrentPages() // 获取当前打开过的页面路由数组
            const currentPage = pages[pages.length - 1]
            let fullPath = currentPage.route
            if (Object.keys(currentPage.options).length) {
              fullPath = `/${currentPage.route}?${Object.keys(
                currentPage.options
              ).map(key => `${key}=${currentPage.options[key]}`)
                .join('&')}`
            }
            if (isRefreshing) {
              isRefreshing = false
              uni.removeStorageSync('memberInfo')
              store.$patch((state) => {
                state.memberInfo = {}
              })
              //存储当前路由地址，授权完毕回调
              store.$patch((state) => {
                state.redirectPath = fullPath
              })
              // 如果当前未有登录信息，弹窗时报未登录，有登陆信息则报异常用户信息
              uni.navigateTo({
                url: '/pages/auth/index'
              })
            } else {
              isRefreshing = true
            }
          } else {
            if (responseData['errcode'] != 1121 && data.showToast != 'noMsg') {
              // uni.showToast({ title: responseData.msg, icon: 'none' })
            }
            return resolve(responseData)
          }
        }
      },
      fail: failInfo => {
        return reject(failInfo)
      },
      complete: finInfo => {
        let status = finInfo.statusCode
        switch (status) {
          case 403:
            uni.showToast({
              title: status + '错误，Sorry, 无权限操作。',
              icon: 'none'
            })
            return
          case 404:
            uni.showToast({
              title: status + '错误，Sorry, 服务不存在。',
              icon: 'none'
            })
            return
          case 500:
          case 502:
          case 503:
            uni.showToast({
              title: status + '错误，Sorry, 服务器异常。',
              icon: 'none'
            })
            return
          case 504:
            uni.showToast({
              title: status + '错误，Sorry, 请求超时。',
              icon: 'none'
            })
            return
          default:
            return
        }
      }
    })
  })
}

const miniAppFetchApiCheckLogin = () => {
  if(isFetchCheck){
    isFetchCheck = false
    return new Promise(async (resolve, reject) => {
      uni.login({
        success: async loginCodeInfo => {
          await uni.request({
            url: uniConfig.prodPath + '/wxmini/open/get',
            method: 'POST',
            data: {
              code:loginCodeInfo.code
            },
            header: {
              'Content-Type': 'application/x-www-form-urlencoded',
              appid: uniConfig.appId
            },
            success: async sucInfo => {
              const memberInfo =  sucInfo.data.data
              uni.setStorage({
                key: 'memberInfo',
                data: memberInfo
              })
            },
          })
        },
        fail: () => {
          uni.hideLoading()
        }
      })
    })
  }
}

let isFetchCheck = true
const callers = []


const uniGet = async (params = {}, url) => {
  return uniRequest(params, url,'GET')
  // if(store.memberInfo && store.memberInfo.auth_code){
  //   return uniRequest(params, url,'GET')
  // }else callers.push({params:params,url:url,method:'GET'})
}

const uniPost = async (params = {}, url) => {
  return uniRequest(params, url,'POST')
}

export const uniFetch = {
  uniGet,
  uniPost
}